package com.ctg.behavior.calc.controller;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSON;
import com.ctg.behavior.calc.impala.calculator.CtTracksCalculator;
import com.ctg.behavior.common.calc.CtCalcResult;
import com.ctg.behavior.common.tracks.CtTracksBody;
import com.ctg.behavior.common.tracks.CtTracksRequest;
import com.ctg.behavior.common.tracks.CtTracksResult;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@RestController
@RequestMapping("/api/track/testing")
public class CtTracksController {

	@Autowired
	private CtTracksCalculator tracksCalculator;

	@PostMapping("/report")
	public CtTracksResult tracks(@RequestBody CtTracksRequest request) {
		
		CtTracksResult result = new CtTracksResult();

		CtTracksBody body = request.getReq();

		String appId = body.getAppId();
		// 检查参数
		if (StringUtils.isEmpty(appId)) {
			result.setSuccess(false);
			result.setErrorCode("400");
			result.setErrorMessage("缺少AppId");
			return result;
		}
		String startTime = body.getStartTime();
		// 检查参数
		if (StringUtils.isEmpty(startTime)) {
			result.setSuccess(false);
			result.setErrorCode("400");
			result.setErrorMessage("缺少startTime");
			return result;
		}
		
		CtCalcResult calcResult = tracksCalculator.doCalculator(body);
		if (calcResult instanceof CtTracksResult) {
			result = (CtTracksResult) calcResult;
			return result;
		} else {
			result.setSuccess(false);
			result.setErrorCode("400");
			result.setErrorMessage("响应报文异常");
			log.error(JSON.toJSONString(calcResult));
		}

		return result;
	}
	
}
